package com.songxh.application.impl;

import com.songxh.application.api.LikeService;
import com.songxh.application.dto.like.ArticleLikeDTO;
import com.songxh.core.base.CommonResult;
import com.songxh.core.entity.UserContext;
import com.songxh.core.exception.BizException;
import com.songxh.core.shared.constant.RedisConsts;
import com.songxh.core.utils.LoginUtils;
import com.songxh.core.utils.RedisUtils;
import com.songxh.shared.enums.LikeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author songxh
 * @create 2023-01-29-10:58
 */
@Slf4j
@Service
public class LikeManagerServiceImpl implements LikeService {

    /**
     * 对文章的点赞进行处理
     *
     * @param articleLikeDTO
     * @return
     */
    @Override
    public CommonResult likeOrCancelLikeArticle(ArticleLikeDTO articleLikeDTO) {
        UserContext userContext = LoginUtils.get();
        Long userId = userContext.getId();
        //1.点赞接口要利用redis做点赞次数限制，限制为半分钟15次
        int requestNum = 0;
        String limitTimesKey = "";
        //区分点赞的是文章还是评论
        if (articleLikeDTO.getCommentId() == null) {
            //文章
            limitTimesKey = String.format(RedisConsts.S_LIKE_LIMIT_TIMES, articleLikeDTO.getArticleId(), userId, "00");
        } else {
            //评论
            limitTimesKey = String.format(RedisConsts.S_LIKE_LIMIT_TIMES, articleLikeDTO.getArticleId(), userId, articleLikeDTO.getCommentId());
        }
        if (RedisUtils.get(limitTimesKey, Integer.class) == null) {
            RedisUtils.set(limitTimesKey, requestNum, 30);//30秒
        }
        if (RedisUtils.get(limitTimesKey, Integer.class) < 15) {//30秒内点击15此以上便警告
            RedisUtils.increment(limitTimesKey, 1L);
        } else {
            throw new BizException("请勿频繁点击【点赞】按钮");
        }

        //点赞数量的key
        String likeCountsKey = RedisConsts.S_LIKE_KEY;
        //2、对点赞数量进行处理
        //hash的key  文章id + 用户id + 评论id，注意，每个用户对文章或评论只能点一次赞，故而点了赞该key便存在，否则就不存在
        String likeHashKey = String.format(RedisConsts.S_LIKE_HASH_KEY, articleLikeDTO.getArticleId(), userId, articleLikeDTO.getCommentId());
        if (RedisUtils.getHash(likeCountsKey, likeHashKey, Long.class) == null) {
            //如果该key不存在，便是点赞
            RedisUtils.setHash(likeCountsKey, likeHashKey, 1L);
        }else {
            //存在key，便是取消点赞，删除该key
            RedisUtils.deleteHash(likeCountsKey, likeHashKey);
        }

        /*if (articleLikeDTO.getLikeStatus().equals(LikeEnum.LIKE.getCode())) {
            //如果目前是取消点赞，那么对点赞数量减一
            RedisUtils.incrementHash(likeCountsKey, likeHashKey, -1L);
        } else if (articleLikeDTO.getLikeStatus().equals(LikeEnum.CANCEL_LIKE.getCode())) {
            //如果是点赞 那么数量加一
            RedisUtils.incrementHash(likeCountsKey, likeHashKey, 1L);
        } else {
            throw new BizException("点赞状态不正确");
        }*/

        return CommonResult.success();
    }
}
